/*
 * @Date: 2022-05-20 09:43:27
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-05-20 13:38:48
 * @FilePath: \my-react-components\src\component\Menu\index.tsx
 * @Description: 菜单组件
 */
import React, { memo, createContext, useState } from "react";
import classNames from "classnames";
import { MenuItemProps } from "./MenuItem";
type SelectCB = (selectIndex: string) => void;
export interface IMenu {
  defaultIndex?: string;
  className?: string;
  mode?: "horizontal" | "vertical";
  style?: React.CSSProperties;
  onSelect?: SelectCB;
  children?: React.ReactNode;
  defalutOpenSubMenu?: string[];
}
interface IMenuContext {
  index: string;
  onSelect?: SelectCB;
  mode?: "horizontal" | "vertical";
  defalutOpenSubMenu?: string[];
}

export const menuContext = createContext<IMenuContext>({ index: "0" });
const Menu: React.FC<IMenu> = memo(
  ({
    defaultIndex,
    className,
    mode,
    style,
    onSelect,
    children,
    defalutOpenSubMenu,
  }) => {
    const [currrentActive, setCurrrentActive] = useState(defaultIndex);
    const classes = classNames("sailor-menu", className, {
      "menu-vertical": mode === "vertical",
      "menu-horizontal": mode === "horizontal",
    });
    const renderChildren = () => {
      return React.Children.map(children, (child, index) => {
        const childrenEl =
          child as React.FunctionComponentElement<MenuItemProps>;
        const { displayName } = childrenEl.type;
        if (displayName === "MenuItem" || displayName === "SubMenu") {
          return React.cloneElement(childrenEl, {
            index: index.toString(),
          });
        } else {
          console.error("在Menu组件中子组件只能使用'MenuItem'或者'SubMenu'");
        }
      });
    };
    const handleClick = (index: string) => {
      setCurrrentActive(index);
      if (onSelect) {
        onSelect(index);
      }
    };
    const context: IMenuContext = {
      index: currrentActive ? currrentActive : "0",
      onSelect: handleClick,
      mode,
      defalutOpenSubMenu,
    };
    return (
      <ul className={classes} style={style} data-testid="test-menu">
        <menuContext.Provider value={context}>
          {renderChildren()}
        </menuContext.Provider>
      </ul>
    );
  },
);

Menu.defaultProps = {
  defaultIndex: "0",
  mode: "horizontal",
  defalutOpenSubMenu: [],
};
export default Menu;
